/**
 * Created by xc on 15/12/22.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');


// Schema 结构
var TgKeywordRModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //`doc_id` bigint(20) unsigned NOT NULL COMMENT '模版ID',
  //`type_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '分类:1单页,2多页,3ppt',
  //`key_id` bigint(20) unsigned NOT NULL COMMENT '关键词ID',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0'


};
TgKeywordRModel.prototype = new ItbBaseModel();

// 取得表名
TgKeywordRModel.prototype.getTableName = function(){
    return 'tg_keyword_r';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
TgKeywordRModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'doc_id=' + this.doc_id + ' and key_id=' + this.key_id;
}

//------------------------------------------------------------------
// 根据设计id取所有关键词
// grpBy: 1按照type分组
TgKeywordRModel.prototype.getKeyByDesignId = function(callback, grpBy){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = ' SELECT t2.key_id, t2.key_name, t2.type, t2.type_name ' +
            ' FROM tg_keyword_r t1, tg_keyword t2 ' +
            ' WHERE t1.doc_id = '+THIS.design_id+
            ' AND t1.key_id = t2.key_id AND t1.del_flg = 0 AND t2.del_flg = 0 ';
        if(!!THIS.type){
            sql += ' AND t2.type='+THIS.type;
        }
        if(THIS.design_kind==20) {
            // 视频模版
            sql += ' AND t1.type_id IN (1020) ';
        } else {
            sql += ' AND t1.type_id NOT IN (1020) ';
        }
        sql += ' ORDER BY t2.type, t2.order ';
        //var sqlValue = [THIS.design_id];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            if(result && result.length>0){
                if(grpBy == 1) {
                    var retInfo = [];
                    var sub = new Array();

                    var type = result[0].type;
                    var typeNm = result[0].type_name;

                    for(var i in result){
                        if(type != result[i].type) {
                            retInfo.push({
                                type: type,
                                type_name: typeNm,
                                sub: sub
                            });

                            type = result[i].type;
                            typeNm = result[i].type_name;

                            sub = new Array();
                        }

                        sub.push({
                            key_id: result[i].key_id,
                            key_name: result[i].key_name
                        });

                        if(i==result.length-1) {// 最后一条
                            retInfo.push({
                                type: type,
                                type_name: typeNm,
                                sub: sub
                            });
                        }
                    }
                    return callback(error, retInfo);

                } else {
                    return callback(error, result);
                }

            } else {
                return callback(error, null);
            }
        });
    });
}

//------------------------------------------------------------------
// 设计师关键词页面用
// 参数 design_kind: 10静态模版, 20视频模版
// 参数 design_id: 设计模版id
// 参数 grpBy: 1按照type分组
TgKeywordRModel.prototype.getDesignKey4Web = function(callback, grpBy){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        var topTypes = '1,2';
        if(THIS.design_kind==20) {
            topTypes = '1020';
        }

        // Use the connection
        var sql = ' SELECT distinct tt.key_id, tt.key_name, tt.type, tt.type_name, tt.doc_id FROM ( '+
            ' SELECT t.key_id, t.key_name, t.type, t.type_name, t.order, t2.doc_id, t2.update_time '+
            ' FROM tg_keyword t '+
            ' LEFT JOIN tg_keyword_r t2 '+// 非自定义关键词
            ' ON t.key_id=t2.key_id AND t2.del_flg=0 AND t2.type_id IN ('+topTypes+') AND t2.doc_id='+THIS.design_id+
            ' WHERE t.del_flg=0 AND t.type!=10 '+
            ' UNION ALL '+
            ' SELECT t.key_id, t.key_name, t.type, t.type_name, t.order, t2.doc_id, t2.update_time '+
            ' FROM tg_keyword t, tg_keyword_r t2 '+// 自定义关键词
            ' WHERE t.del_flg=0 AND t.type=10 AND t2.key_id=t.key_id '+
            ' AND t2.del_flg=0 AND t2.type_id IN ('+topTypes+') AND t2.doc_id='+THIS.design_id+
            ' ) tt '+
            ' ORDER BY tt.type, tt.order, tt.update_time ';
        //var sqlValue = [THIS.design_id];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            if(result && result.length>0){
                if(grpBy == 1) {
                    var retInfo = [];
                    var sub = new Array();

                    var type = result[0].type;
                    var typeNm = result[0].type_name;

                    for(var i=0; i<result.length; i++){
                        if(type != result[i].type) {
                            retInfo.push({
                                type: type,
                                type_name: typeNm,
                                keys: sub
                            });

                            type = result[i].type;
                            typeNm = result[i].type_name;

                            sub = new Array();
                        }

                        sub.push({
                            "key_id": result[i].key_id,
                            "key_name": result[i].key_name,
                            "design_id": result[i].doc_id||0
                        });

                        if(i==result.length-1) {// 最后一条
                            retInfo.push({
                                type: type,
                                type_name: typeNm,
                                keys: sub
                            });
                        }
                    }
                    return callback(error, retInfo);

                } else {
                    return callback(error, result);
                }

            } else {
                return callback(error, null);
            }
        });
    });
};

//------------------------------------------------------------------
// 清除指定设计模版的关键词
TgKeywordRModel.prototype.delDocKey = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'UPDATE tg_keyword_r '+
            ' SET del_flg=1, update_time=sysdate(), update_by= '+THIS.update_by+
            ' WHERE del_flg = 0 AND doc_id='+ THIS.doc_id+
            ' AND type_id='+THIS.type_id;


        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
};

//------------------------------------------------------------------
/**
 * 清除指定设计模版的关键词
 *
 * @param userId  用户的唯一标识
 * @param designId 设计模板id
 *
 *
  */
TgKeywordRModel.prototype.delDesignKeys = function(userId,designId,callback){
    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = "	UPDATE	" +
            "	  itbour.tg_keyword_r tkr	" +
            "	SET	" +
            "	  tkr.del_flg = 1,	" +
            "	  tkr.update_by = "+userId+",	" +
            "	  tkr.update_time = SYSDATE()	" +
            "	WHERE tkr.doc_id = "+designId+"	" +
            "	  AND tkr.del_flg = 0	" ;
            connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();
            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
};

//------------------------------------------------------------------
/**
 * 插入指定设计模版的关键词
 *
 * @param userId  用户的唯一标识
 * @param designId 设计模板id
 * @param defKeyIds 关键词id数组
 * @param type 设计模板类型
 *
 */
TgKeywordRModel.prototype.insertNewDesignKeyword = function(userId,designId,defKeyIds,type,callback){
    pool.pool.getConnection(function(err, connection) {

        var sql ="	INSERT INTO itbour.tg_keyword_r 	" +
            "	(doc_id,type_id,key_id,create_time,update_time,update_by,del_flg)	" +
            "	VALUES	" ;
        for(var i=0;i<defKeyIds.length;i++){
            if(i==defKeyIds.length-1){
                sql+="  ("+designId+","+type+","+defKeyIds[i]+",SYSDATE(),SYSDATE(),"+userId+",0)";
            }
            if(i!=defKeyIds.length-1){
                sql+=" ("+designId+","+type+","+defKeyIds[i]+",SYSDATE(),SYSDATE(),"+userId+",0),";
            }
        }
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();
            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
};

//------------------------------------------------------------------
// 导出
module.exports = TgKeywordRModel;